package com.zhanghe.security.filter;

import com.zhanghe.security.filter.auth2.GithubAuthFilter;
import com.zhanghe.security.property.SecurityProperties;
import com.zhanghe.security.util.JwtUtil;
import com.zhanghe.security.util.R;
import com.zhanghe.security.util.ResponseUtil;
import com.zhanghe.security.util.ReturnCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NormalLoginFilter extends AbstractAuthenticationProcessingFilter {

    protected static final Logger logger = LoggerFactory.getLogger(NormalLoginFilter.class);

    @Autowired
    private SecurityProperties securityProperties;

    public NormalLoginFilter(String defaultFilterProcessesUrl,AuthenticationManager authenticationManager) {
        super(defaultFilterProcessesUrl);
        setAuthenticationManager(authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {
        String userName = httpServletRequest.getParameter("userName");
        String password = httpServletRequest.getParameter("password");
        return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(userName,password));
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
        logger.debug("normal登录成功");
        Map<String,Object> params = new HashMap<String,Object>();
        List<String> roles = new ArrayList<String>();
        for(GrantedAuthority authority:authResult.getAuthorities()){
            roles.add(authority.getAuthority());
        }
        params.put("roles",roles);
        String access_token = JwtUtil.sign(authResult.getName(),params,securityProperties.getTokensecret(),securityProperties.getTokenExpireMinutes() * 60 * 1000);
        String refresh_token = JwtUtil.sign(authResult.getName(),new HashMap<String,Object>(0),securityProperties.getTokensecret(),securityProperties.getRefreshTokenExpireTime() * 60 * 1000);
        R r = new R(access_token,refresh_token);
        ResponseUtil.writeResponse(request,response,r.toString(),securityProperties.getOrigins());
    }

    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
        logger.debug("normal登录失败:{}",failed.getMessage());
        R r = new R(ReturnCode.GITHUB_LOGIN_FAILED,"");
        ResponseUtil.writeResponse(request,response,r.toString(),securityProperties.getOrigins());
    }
}
